import MD5 from 'md5'
import { getToken, getSubject } from '@/utils/storage'
import appConfig from '@/config'
import { getURLParameters } from '@/utils/index'
import store from '@/store'

const { appKey, appSecret, clientId } = appConfig

const getParamStr = params => {
  return Object.keys(params)
    .filter(i => params[i] !== undefined)
    .sort((n, m) => {
      var a = n
      var b = m
      if (a < b) return -1
      if (a > b) return 1
      return 0
    })
    .map(key => `${key}=${params[key]}`)
    .join('&')
}
const encryptHandler = Vue => ({
  requestResolve(config) {
    const { method, params = {}, url, data, needOperator = true } = config
    // 后台没有统一dns的容器获取操作人，我们先手动加,真的啦跨
    if (config.method.toLowerCase() !== 'get' && needOperator) {
      config.data.operator = store.getters.name || 'linjun'
      config.headers['operator'] = store.state.user?.name?.info?.claims?.preferred_username || 'linjun'
    }
    const timestamp = +new Date()
    if (method.toLowerCase() === 'get') {
      const query = {
        ...getURLParameters(url),
        ...params,
        appid: appKey,
        timestamp
      }
      params.appid = appKey
      params.timestamp = timestamp
      params.sign = MD5(`${getParamStr(query)}&key=${appSecret}`)
      config.params = params
    } else {
      const query = {
        ...getURLParameters(url),
        timestamp,
        appid: appKey
      }
      let sign

      if (data instanceof FormData) {
        sign = MD5(`${getParamStr(query)}&key=${appSecret}`)
      } else {
        sign = MD5(
          `${getParamStr(query)}&${JSON.stringify(data)}&key=${appSecret}`
        )
      }
      // const sign = MD5(
      //   `${getParamStr(query)}&${JSON.stringify(data)}&key=${appSecret}`
      // )
      config.url = `${config.url}${
        config.url.includes('?') ? '&' : '?'
      }appid=${appKey}&timestamp=${timestamp}&sign=${sign}`
    }

    // 设置token
    const token = getToken()
    const subject = getSubject()

    if (token && subject) {
      config.headers['token'] = token
      config.headers['subject'] = subject
    }
    config.headers['client-id'] = clientId
    return config
  }
})
export default encryptHandler
